package cn.livingCloud.controller.content.front;

import cn.livingCloud.dto.SettingDto;
import cn.livingCloud.service.AutoReplyService;
import cn.livingCloud.service.SettingService;
import cn.livingCloud.wechat.exception.SignatureErrorException;
import cn.livingCloud.wechat.handler.InputStreamUtils;
import cn.livingCloud.wechat.handler.RequestMsgProcess;
import cn.livingCloud.wechat.protocol.req.CheckServerAddress;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by sujiantang on 2015/12/11.
 */
@Controller
@RequestMapping("/wechat")
public class AutoReplyController {
    private static final Logger LOG = Logger.getLogger(AutoReplyController.class);

    @Autowired
    private AutoReplyService replyService;
    @Autowired
    private SettingService settingService;

    @RequestMapping(value = "/msg", method = RequestMethod.POST)
    @ResponseBody
    public String processMsg(HttpServletRequest request) throws IOException {
        LOG.debug("===========================开始消息处理===========================");
        String requestXml = InputStreamUtils.readString(request.getInputStream());
        LOG.debug("请求的xml:" + requestXml);
        RequestMsgProcess process = new RequestMsgProcess(replyService);
        String result = process.process(requestXml);
        LOG.debug("消息处理结果:" + result);
        LOG.debug("===========================消息处理完成===========================");
        return result;
    }

    /**
     * 验证服务器地址
     */
    @RequestMapping(value = "/msg", method = RequestMethod.GET)
    @ResponseBody
    public String checkAddress(CheckServerAddress address) {
        try {
            SettingDto settingDto = settingService.findSetting();
            return address.check(settingDto.getToken());
        } catch (SignatureErrorException e) {
            e.printStackTrace();
        }
        return "";
    }
}
